var z = new zjm();
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substring(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
function numberToChinese(num) {
    let chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    let chnUnitSection = ["", "万", "亿", "万亿", "亿亿"];
    let chnUnitChar = ["", "十", "百", "千"];
    function sectionToChinese(section) {
        let strIns = '',
            chnStr = '';
        let unitPos = 0;
        let zero = true;
        while (section > 0) {
            let v = section % 10;
            if (v === 0) {
                if (!zero) {
                    zero = true;
                    chnStr = chnNumChar[v] + chnStr;
                }
            } else {
                zero = false;
                strIns = chnNumChar[v];
                strIns += chnUnitChar[unitPos];
                chnStr = strIns + chnStr;
            }
            unitPos++;
            section = Math.floor(section / 10);
        }
        return chnStr;
    }
    let unitPos = 0;
    let strIns = '',
        chnStr = '';
    let needZero = false;
    if (num === 0) {
        return chnNumChar[0];
    }
    while (num > 0) {
        let section = num % 10000;
        if (needZero) {
            chnStr = chnNumChar[0] + chnStr;
        }
        strIns = sectionToChinese(section);
        strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
        chnStr = strIns + chnStr;
        needZero = (section < 1000) && (section > 0);
        num = Math.floor(num / 10000);
        unitPos++;
    }
    return chnStr;
}
$(document).ready(function () {
    z.ax(
        "get",
        "/novel/NovelChapter/selectByChapterId/" + getQueryString("chapterID"),
        null,
        (res) => {
            $(".chapter-title h1").text(`第${numberToChinese(res.chapterNum)}章：${res.chapterTitle}`);
            console.log(res);
            z.ax(
                "get",
                "/novel/NovelChapter/" + res.novelId,
                null,
                (res2) => {
                    for (var i = 0; i < res2.length; i++) {
                        $(".list-group").append(`
                            <li class="list-group-item ${i + 1 == res.chapterNum ? "active" : ""}"><a href="#">第${numberToChinese(res2[i].chapterNum)}章：${res2[i].chapterTitle}</a></li>
                        `);
                    }
                    // 更新章节导航按钮状态
                    updateChapterNavButtons();
                }
            );
        }
    );
    // 初始化变量
    let currentFontSize = 16; // 默认字体大小
    let currentLineHeight = 1.8; // 默认行高
    let currentParagraphSpacing = 1; // 默认段落间距
    let currentTextColor = '#333333'; // 默认文字颜色
    let currentBgColor = '#ffffff'; // 默认背景颜色
    let currentFontFamily = 'serif'; // 默认字体
    let isNightMode = false; // 默认不是夜间模式

    // DOM 元素缓存
    const $chapterContent = $('.chapter-content');
    const $fontSizeDisplay = $('.font-size-display');
    const $lineHeightDisplay = $('.line-height-display');
    const $paragraphSpacingDisplay = $('.paragraph-spacing-display');
    const $sidebar = $('#chapter-sidebar');
    const $settingsPanel = $('#settings-panel');
    const $bookmarkPanel = $('.bookmark-panel');
    const $themeToggle = $('#theme-toggle');

    // 书签面板切换
    $('.add-bookmark').click(function () {
        $bookmarkPanel.toggleClass('open');
    });

    $('.close-bookmark').click(function () {
        $bookmarkPanel.removeClass('open');
    });

    // 移除书签
    $('.remove-bookmark').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).closest('.bookmark-item').fadeOut(300, function () {
            $(this).remove();
            // 如果没有书签了，隐藏书签面板
            if ($('.bookmark-list li').length === 0) {
                $bookmarkPanel.removeClass('open');
            }
        });
    });

    // 添加当前位置到书签
    $('#add-current-bookmark').click(function () {
        const chapterTitle = $('.chapter-title h1').text();
        // 简单模拟获取当前阅读位置
        const currentPosition = "第" + Math.floor(Math.random() * 10 + 1) + "段";

        // 创建新书签项
        const newBookmark = $('<li class="bookmark-item list-group-item">' +
            '<a href="#">' + chapterTitle + ' - ' + currentPosition + '</a>' +
            '<button class="remove-bookmark btn btn-xs btn-danger"><i class="fa fa-trash-o"></i></button>' +
            '</li>');

        // 添加到书签列表
        $('.bookmark-list ul').append(newBookmark);

        // 为新书签添加删除事件
        newBookmark.find('.remove-bookmark').click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            newBookmark.fadeOut(300, function () {
                newBookmark.remove();
                if ($('.bookmark-list li').length === 0) {
                    $bookmarkPanel.removeClass('open');
                }
            });
        });

        // 显示添加成功的提示效果
        newBookmark.hide().fadeIn(500);
    });

    // 字体大小调整
    $('.increase-font').click(function () {
        if (currentFontSize < 24) { // 最大字体限制
            currentFontSize += 2;
            updateFontSettings();
        }
    });

    $('.decrease-font').click(function () {
        if (currentFontSize > 12) { // 最小字体限制
            currentFontSize -= 2;
            updateFontSettings();
        }
    });

    // 行高调整最小1.2最大3.0
    $('.increase-line-height').click(function () {
        if (currentLineHeight < 3.0) { // 最大行高限制
            currentLineHeight += 0.2;
            currentLineHeight = parseFloat(currentLineHeight.toFixed(1)); // 保留一位小数
            updateFontSettings();
        }
    });

    $('.decrease-line-height').click(function () {
        if (currentLineHeight > 1.2) { // 最小行高限制
            currentLineHeight -= 0.2;
            currentLineHeight = parseFloat(currentLineHeight.toFixed(1)); // 保留一位小数
            updateFontSettings();
        }
    });

    // 段落间距调整最小0.5最大2。0
    $('.increase-paragraph').click(function () {
        if (currentParagraphSpacing < 2.0) { // 最大段落间距限制
            currentParagraphSpacing += 0.2;
            currentParagraphSpacing = parseFloat(currentParagraphSpacing.toFixed(1)); // 保留一位小数
            updateFontSettings();
        }
    });

    $('.decrease-paragraph').click(function () {
        if (currentParagraphSpacing > 0.5) { // 最小段落间距限制
            currentParagraphSpacing -= 0.2;
            currentParagraphSpacing = parseFloat(currentParagraphSpacing.toFixed(1)); // 保留一位小数
            updateFontSettings();
        }
    });

    // 字体选择
    $('.font-family-select').change(function () {
        currentFontFamily = $(this).val();
        updateFontSettings();
    });

    // 文字颜色选择
    $('.text-colors .color-option').click(function () {
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        currentTextColor = $(this).data('color');
        updateFontSettings();
    });

    // 背景颜色选择
    $('.bg-colors .color-option').click(function () {
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        currentBgColor = $(this).data('color');
        updateFontSettings();
    });

    // 阅读模式切换（白天/黑夜）
    $('input[name="reading-mode"]').change(function () {
        if ($(this).val() === 'night') {
            enableNightMode();
        } else {
            disableNightMode();
        }
    });

    // 顶部夜间模式快速切换
    $themeToggle.click(function () {
        if (isNightMode) {
            disableNightMode();
            $('input[name="reading-mode"][value="day"]').prop('checked', true);
        } else {
            enableNightMode();
            $('input[name="reading-mode"][value="night"]').prop('checked', true);
        }
    });

    // 章节切换
    $('.prev-chapter').click(function () {
        // 这里只是模拟章节切换效果
        if (!$(this).hasClass('disabled')) {
            showChapterChangeEffect();
            // 获取当前活跃章节
            const $currentActive = $('.chapter-list .list-group-item.active');
            // 切换到上一章
            $currentActive.prev().find('a').click();
        }
    });

    $('.next-chapter').click(function () {
        // 这里只是模拟章节切换效果
        if (!$(this).hasClass('disabled')) {
            showChapterChangeEffect();
            // 获取当前活跃章节
            const $currentActive = $('.chapter-list .list-group-item.active');
            // 切换到下一章
            $currentActive.next().find('a').click();
        }
    });

    // 章节列表点击
    $('.chapter-list .list-group-item a').click(function (e) {
        e.preventDefault();
        // 移除之前的活跃状态
        $('.chapter-list .list-group-item').removeClass('active');
        // 添加当前活跃状态
        $(this).parent().addClass('active');
        // 更新章节标题
        $('.chapter-title h1').text($(this).text());
        // 显示章节切换效果
        showChapterChangeEffect();
    });

    // 更新章节导航按钮状态
    function updateChapterNavButtons() {
        const activeIndex = $('.chapter-list .list-group-item.active').index();
        const totalChapters = $('.chapter-list .list-group-item').length;

        // 第一章
        if (activeIndex === 0) {
            $('.prev-chapter').addClass('disabled');
            $('.next-chapter').removeClass('disabled');
        }
        // 最后一章
        else if (activeIndex === totalChapters - 1) {
            $('.prev-chapter').removeClass('disabled');
            $('.next-chapter').addClass('disabled');
        }
        // 中间章节
        else {
            $('.prev-chapter').removeClass('disabled');
            $('.next-chapter').removeClass('disabled');
        }
    }

    // 重置所有设置
    $('.reset-settings button').click(function () {
        // 重置变量
        currentFontSize = 16;
        currentLineHeight = 1.8;
        currentParagraphSpacing = 1;
        currentTextColor = '#333333';
        currentBgColor = '#ffffff';
        currentFontFamily = 'serif';

        // 重置UI
        $fontSizeDisplay.text(currentFontSize + 'px');
        $lineHeightDisplay.text(currentLineHeight);
        $paragraphSpacingDisplay.text(currentParagraphSpacing + 'em');
        $('.font-family-select').val(currentFontFamily);

        // 重置颜色选择
        $('.text-colors .color-option').removeClass('active');
        $(`.text-colors .color-option[data-color="${currentTextColor}"]`).addClass('active');

        $('.bg-colors .color-option').removeClass('active');
        $(`.bg-colors .color-option[data-color="${currentBgColor}"]`).addClass('active');

        // 重置为白天模式
        disableNightMode();
        $('input[name="reading-mode"][value="day"]').prop('checked', true);

        // 更新样式
        updateFontSettings();

        // 显示重置提示
        alert('所有设置已重置为默认值');
    });

    // 更新字体设置
    function updateFontSettings() {
        $fontSizeDisplay.text(currentFontSize + 'px');
        $lineHeightDisplay.text(currentLineHeight);
        $paragraphSpacingDisplay.text(currentParagraphSpacing + 'em');

        $chapterContent.css({
            'font-size': currentFontSize + 'px',
            'line-height': currentLineHeight,
            'color': currentTextColor,
            'background-color': currentBgColor,
            'font-family': currentFontFamily
        });

        // 设置段落间距
        $chapterContent.find('p').css('margin-bottom', currentParagraphSpacing + 'em');
    }

    // 启用夜间模式
    function enableNightMode() {
        isNightMode = true;
        $('body').addClass('night-mode');
        $themeToggle.html('<i class="fa fa-sun-o"></i> 白天模式');
    }

    // 禁用夜间模式
    function disableNightMode() {
        isNightMode = false;
        $('body').removeClass('night-mode');
        $themeToggle.html('<i class="fa fa-moon-o"></i> 夜间模式');
    }

    // 章节切换动画效果
    function showChapterChangeEffect() {
        $chapterContent.fadeOut(300, function () {
            // 这里可以加载新章节内容
            $chapterContent.fadeIn(300);
        });
    }

    // 点击页面其他区域关闭书签面板
    $(document).click(function (e) {
        // 如果点击的不是书签面板或其触发按钮，则关闭
        if (!$(e.target).closest($bookmarkPanel).length &&
            !$(e.target).closest('.add-bookmark').length) {
            $bookmarkPanel.removeClass('open');
        }
    });

    // 初始化页面设置
    updateFontSettings();
    updateChapterNavButtons();
});
